import React, {PropsWithChildren, useState} from 'react'
import RefreshableSelectFormItem from "./RefreshableSelectFormItem";
import {Button, Form, Select, SelectProps} from "antd";
import SingleInputPopover from "./SingleInputPopover";
import {PlusOutlined} from "@ant-design/icons";
import FormItem from "antd/es/form/FormItem";

export interface QuickCreatableSelectFormItemProps extends PropsWithChildren {
    name:string
    label:string
    onRefresh?: () => Promise<any>
    options:QuickCreatableSelectFormItemOption[]
    onCreate: (name:string)=> Promise<any>
    required?:boolean
    mode?:SelectProps["mode"]
}

export interface QuickCreatableSelectFormItemOption{
    label: React.ReactNode
    value: any
}

const QuickCreatableSelectFormItem: React.FC<QuickCreatableSelectFormItemProps> = ({label,onRefresh,options,name,onCreate,required,mode}) => {
    const [creating,setCreating] = useState(false)
    return <>
        <div style={{display: 'inline-flex', alignItems: "center",width:"auto",justifyContent:"start"}}>
            <div style={{flexGrow: 1}}>
                <RefreshableSelectFormItem label={label} name={name} onRefresh={onRefresh}
                                           required={required}
                                           builder={refreshing =>
                                         <Select placeholder={`选择${label}`} mode={mode} style={{width: 200}} showSearch
                                                 filterOption={(input: string, option?) => {
                                                     return (option?.children as unknown as string).toLowerCase().includes(input.toLowerCase());
                                                 }} loading={refreshing}>
                                             {options.map(item => {
                                                 return <Select.Option key={item.value}
                                                                       value={item.value}>{item.label}</Select.Option>
                                             })}
                                         </Select>}/>
            </div>
            <Form.Item label={" "}>
                <SingleInputPopover title={`新建${label}`} required onConfirm={async value => {
                    setCreating(true)
                    try {
                        await onCreate(value)
                    }finally {
                        setCreating(false)
                    }
                }} fieldName={"名称"}>
                    <FormItem>
                        <Button loading={creating} style={{marginLeft: 8}}>快速新建<PlusOutlined/></Button>
                    </FormItem>
                </SingleInputPopover>
            </Form.Item>
        </div>
    </>
}

export default QuickCreatableSelectFormItem


